import React, { ReactNode, useEffect, useRef, useState } from 'react';
import { motion } from 'framer-motion';
import './index.css';
import { useSiderCollapsed, useTheme } from '@/store/settingsStore.ts';
import { style, ThemeMode } from '@ycx/ui';
import { createStyles } from 'antd-style';

const useStyles = (theme: ThemeMode) => {
  const isLight = theme === ThemeMode.Light;
  return createStyles(({ css }) => {
    return {
      container: css`
        background-color: ${isLight
          ? style.neutralColorChartBgLight
          : style.neutralColorChartBgtDark};
      `,
      slider: css`
        border: 0.5px solid
          ${isLight ? style.borderColorContainerLight : style.borderColorContainerDark};
        background-color: ${isLight ? style.bgColorContainerLight : style.bgColorContainerDark};
      `,
      option: css`
        transition: color 0.3s ease;

        &:hover {
          background: rgba(0, 0, 0, 0.1);
        }

        &:focus {
          outline: none;
          background-color: unset;
        }
      `,
    };
  });
};

type Option = {
  value: string | number;
  label: ReactNode;
};

interface SegmentedProps {
  value?: string | number;
  options: Option[];
  onChange?: (val: string | number) => void;
}

// 迫于antd的Segmented不支持垂直排列，其他需要Segmented的请使用antd的
const Segmented: React.FC<SegmentedProps> = ({ options, onChange, value }) => {
  const theme = useTheme();
  const collapsed = useSiderCollapsed();

  const { styles } = useStyles(theme)();

  const [selectedIndex, setSelectedIndex] = useState<number>(
    options.findIndex((option) => option.value === value),
  );
  const [backgroundStyle, setBackgroundStyle] = useState({
    size: 0,
    left: 0,
    top: 0,
  });
  const containerRef = useRef<HTMLDivElement>(null);
  const optionRefs = useRef<(HTMLButtonElement | null)[]>([]);

  const handleOptionClick = (index: number) => {
    setSelectedIndex(index);
    onChange?.(options[index].value);
  };

  useEffect(() => {
    const selectedButton = optionRefs.current[selectedIndex];
    const container = containerRef.current;
    if (selectedButton && container) {
      setBackgroundStyle({
        size: selectedButton.clientWidth,
        left: selectedButton.offsetLeft - 2,
        top: selectedButton.offsetTop - 2,
      });
    }
  }, [selectedIndex, collapsed]);

  return (
    <div
      className={`relative inline-flex rounded-lg p-0.5 ${styles.container} ${collapsed ? 'flex-col' : 'flex-row'}`}
      ref={containerRef}
    >
      {options.map((option, index) => (
        <button
          key={option.value}
          ref={(el) => (optionRefs.current[index] = el)}
          className={`${styles.option} relative z-10 cursor-pointer rounded-md border-none bg-none`}
          onClick={() => handleOptionClick(index)}
          style={{ color: index === selectedIndex ? 'rgba(0,0,0,0.88)' : 'rgba(0,0,0,0.65)' }}
        >
          {option.label}
        </button>
      ))}
      <motion.div
        className={`${styles.slider} absolute bottom-0.5 top-0.5 rounded-md`}
        initial={false}
        animate={{
          width: backgroundStyle.size,
          height: backgroundStyle.size,
          x: collapsed ? 0 : backgroundStyle.left,
          y: collapsed ? backgroundStyle.top : 0,
        }}
        transition={{
          type: 'spring',
          stiffness: 500,
          damping: 40,
        }}
      />
    </div>
  );
};

export default Segmented;
